package com.example.fruit;

import org.andengine.engine.Engine;
import org.andengine.engine.LimitedFPSEngine;
import org.andengine.engine.camera.BoundCamera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.scene.CameraScene;
import org.andengine.entity.scene.Scene;
import org.andengine.ui.activity.BaseGameActivity;

import activity.RegisterActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.example.input.topscore;
import com.example.manager.ResourcesManager;
import com.example.manager.SceneManager;
import com.example.scene.LoginScene;
import com.example.scene.ServerScore;

public class GameActivity extends BaseGameActivity {
	public static int CAMERA_WIDTH = 720;
	public static int CAMERA_HEIGHT = 480;
	 
	public static Handler mHandler = null;
	public BoundCamera mCamera;
	private ResourcesManager resourcesManager;
	public Scene mMainScene;
	public CameraScene mPauseScene;
	//public static ArrayList<AnimatedSprite> mArrTiledTextureRegion = new ArrayList<AnimatedSprite>();
	/*public ArrayList<ITextureRegion> mArrFruit = new ArrayList<ITextureRegion>();
	public ArrayList<Integer> mArrFruitId = new ArrayList<Integer>();
	public ArrayList<ITextureRegion> mArrBoom = new ArrayList<ITextureRegion>();
	public ArrayList<Integer> mArrBoomId = new ArrayList<Integer>();
	*/
	public int width;
	public int height;
	final int DANHSACH_MESSAGE=1;
	final int ERROR_MESSAGE=2;
	final int LOGIN_MESSAGE=3;
	final int MESSAGE=4;
	final int LOGIN_UPDATESCORE_MESSAGE=5;
	final int UPDATE_SCORE_MESSAGE=6;
	final int WAITING=8;
	final int EXIT=9;
	@Override
	public Engine onCreateEngine(EngineOptions pEngineOptions) 
	{
		mHandler = new Handler();
		return new LimitedFPSEngine(pEngineOptions, 60);
	}
	public ConnectivityManager getManagerNetwork()
	{
		final ConnectivityManager connMgr = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		return connMgr;
	}
	/*public boolean isInternetOn(Context ctx) {
        this.mContext = ctx;
        ConnectivityManager Connect_Manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        State connected = NetworkInfo.State.CONNECTED;
        State connecting = NetworkInfo.State.CONNECTING;
        State disconnected = NetworkInfo.State.DISCONNECTED;

        State info0 = Connect_Manager.getNetworkInfo(0).getState();
        State info1 = Connect_Manager.getNetworkInfo(1).getState();

        // ARE WE CONNECTED TO THE NET
        if (info0 == connected || info0 == connecting || info1 == connecting
                || info1 == connected) {

            Log.d("Internet", "Connected");
            return true;
        } else if (info0 == disconnected || info1 == disconnected) {
            Log.d("Internet", "DisConnected");
            return false;
        }
        return false;
    }*/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{  
		if (keyCode == KeyEvent.KEYCODE_BACK)
	    {
	    	SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
	    }
		if (keyCode == KeyEvent.KEYCODE_MENU)
	    {
	    	//System.exit(0);
	    }
	    return false; 
	}
	
	@Override
	public EngineOptions onCreateEngineOptions() {

		width = getWindowManager().getDefaultDisplay().getWidth();
		height = getWindowManager().getDefaultDisplay().getHeight();
		mCamera = new BoundCamera(0, 0, this.CAMERA_WIDTH, this.CAMERA_HEIGHT);
		// this.mCamera = new SmoothCamera(0, 0, 960f, 640f, 100, 100, 1.0f);
		EngineOptions engineOptions = new EngineOptions(true,
				ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(),
				this.mCamera);
		// EngineOptions engineOptions = new EngineOptions(true,
		// ScreenOrientation.LANDSCAPE_SENSOR, new RatioResolutionPolicy(1.5f),
		// mCamera;
		engineOptions.getRenderOptions().setDithering(true);
		engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
		// engineOptions.getRenderOptions().getConfigChooserOptions().setRequestedMultiSampling(true);
		engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
		return engineOptions;

	}

	@Override
	public void onCreateResources(
			OnCreateResourcesCallback pOnCreateResourcesCallback)
			throws Exception {
		ResourcesManager.prepareManager(mEngine, this, mCamera, getVertexBufferObjectManager());
	    resourcesManager = ResourcesManager.getInstance();
	    resourcesManager.createSharePreference();
	    pOnCreateResourcesCallback.onCreateResourcesFinished();
	}
	ServerScore server;
	@Override
	public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
			throws Exception {
		server=new ServerScore();
		SceneManager.getInstance().createSplashScene(pOnCreateSceneCallback);
	}

	@Override
	public void onPopulateScene(Scene pScene,
			OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
		// TODO Auto-generated method stub
		mEngine.registerUpdateHandler(new TimerHandler(2f, new ITimerCallback() 
	    {
	        public void onTimePassed(final TimerHandler pTimerHandler) 
	        {
	            mEngine.unregisterUpdateHandler(pTimerHandler);
	            SceneManager.getInstance().createMenuScene();
	        }
	    }));
	    pOnPopulateSceneCallback.onPopulateSceneFinished();
	    
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (this.isGameLoaded())
		{
			System.exit(0);	
		}	
	}
    public String dsscore,error,message;
    public String listcores;
    public topscore[] listscore;
    public ProgressDialog mProgressDialog;
	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
	    case DANHSACH_MESSAGE:
	    	return new AlertDialog.Builder(this)
			.setIcon(R.drawable.score)
			.setTitle("TOP HIGH SCORE!")
			.setCancelable(true)
			.setMessage(dsscore)
			.setPositiveButton("OK", null)
			.create();
	    case ERROR_MESSAGE:
	    	return new AlertDialog.Builder(this)
			.setIcon(R.drawable.score)
			.setTitle("ERROR!")
			.setCancelable(true)
			.setMessage(error)
			.setPositiveButton("OK", null)
			.create();
	    case LOGIN_MESSAGE:
	    	
	    	LayoutInflater inflater = getLayoutInflater();
	    	final View dialoglayout = inflater.inflate(R.layout.lg, (ViewGroup) getCurrentFocus());
	    	return new AlertDialog.Builder(this)
			//.setIcon(R.drawable.score)
			//.setTitle("Login Your Account")
			.setCancelable(true)
			.setView(dialoglayout)
			.setNeutralButton("OK", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					final EditText userInput = (EditText)dialoglayout.findViewById(R.id.user);
					final EditText passInput = (EditText)dialoglayout.findViewById(R.id.pass);
					String user=userInput.getText().toString();
					String pass=passInput.getText().toString();
					
					LoginScene login=new LoginScene(user,pass);
					userInput.setText(null);
					passInput.setText(null);
				}
			})
			.setPositiveButton("Cancel", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			})
			.setNegativeButton("Register", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Intent register=new Intent(getApplicationContext(),RegisterActivity.class);
					startActivity(register);
				}
			})
			.create();
	    case MESSAGE:
	    	return new AlertDialog.Builder(this)
			.setIcon(R.drawable.score)
			.setTitle("Message!")
			.setCancelable(true)
			.setMessage(message)
			.setPositiveButton("OK", null)
			.create();
	    case LOGIN_UPDATESCORE_MESSAGE:
	    	LayoutInflater inflater1 = getLayoutInflater();
	    	final View dialoglayout1 = inflater1.inflate(R.layout.login, (ViewGroup) getCurrentFocus());
	    	return new AlertDialog.Builder(this)
			.setIcon(R.drawable.score)
			.setTitle("Login Your Account")
			.setCancelable(true)
			.setView(dialoglayout1)
			.setNeutralButton("OK", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					final EditText userInput = (EditText)dialoglayout1.findViewById(R.id.user);
					final EditText passInput = (EditText)dialoglayout1.findViewById(R.id.pass);
					String user=userInput.getText().toString();
					String pass=passInput.getText().toString();
					
					LoginScene login=new LoginScene(user,pass);
					userInput.setText(null);
					passInput.setText(null);
				}
			})
			.setPositiveButton("Cancel", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			})
			.create();
	    case UPDATE_SCORE_MESSAGE://cap nhat diem khi da dang nhap roi
	    	return new AlertDialog.Builder(this)
			.setIcon(R.drawable.score)
			.setTitle("Your Account!")
			.setCancelable(true)
			.setMessage(message)
			.setPositiveButton("OK", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					server.updateScore();
				}
			})
			.setNeutralButton("Cancel", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			})
			.create();
	    case 7://cap nhat diem khi da dang nhap roi
	    	return new AlertDialog.Builder(this)
			.setIcon(R.drawable.score)
			.setTitle("Note!")
			.setMessage(message)
			.create();
	    case WAITING:
	    	return new AlertDialog.Builder(this)
			.setIcon(R.drawable.wait)
			.setTitle("Waiting")
			.setMessage("Please Waiting...")
			.create();
	    case EXIT:
	    	return new AlertDialog.Builder(this)
			.setTitle("Exit ")
			.setCancelable(true)
			.setMessage("Are you sure want to quit the game?")
			.setPositiveButton("Exit", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					System.exit(0);
				}
			})
			.setNeutralButton("Keep Playing", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			})
			.create();
	    default:
	        return null;
	    }       
	}
	public void pauseGame() {
		mEngine.stop();
	}
	public void unPauseGame() {
		mEngine.start();
	}
}
